package com.android.aiod.manager;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.widget.Toast;

import java.util.List;
import java.util.Locale;

public class VoiceManager {

    TextToSpeech textToSpeech;
    Context mContext;

    public VoiceManager(Context mContext) {
        this.mContext = mContext;
        init();
    }

    private void init() {
        textToSpeech = new TextToSpeech(mContext, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
//                    int supported = textToSpeech.setLanguage(Locale.CHINA);

                } else {

//                    Toast.makeText(mContext, "语音引擎初始化失败！", Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 设置音调,值越大声音越尖(女生)，值越小则变成男声,1.0是常规
        textToSpeech.setPitch(ConfigManager.instance().configInfo.voice_pitch);
        // 设定语速,默认1.0正常语速
        textToSpeech.setSpeechRate(ConfigManager.instance().configInfo.voice_speed);

        switch (ConfigManager.instance().configInfo.voice_type) {
            case 0:
                switchEngine("com.xiaomi.mibrain.speech");     //小爱语音包
                break;
            case 1:
                switchEngine("com.iflytek.speechcloud");       //讯飞语音包
                break;
            case 2:
                switchEngine("com.baidu.duersdk.opensdk");     //百度语音包
                break;
        }
        textToSpeech.setLanguage(Locale.CHINA);


    }

    /**
     * 获取语音包列表
     */
    public List<TextToSpeech.EngineInfo> getTTSList() {
        return textToSpeech.getEngines();
    }

    //播放语音包
    public void play(String text) {
        textToSpeech.speak(text, TextToSpeech.QUEUE_ADD, null);
    }

    //暂停播放
    public void switchEngine(String engine) {
        try {
            textToSpeech.stop();
            textToSpeech.setEngineByPackageName(engine);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //释放资源
    public void release() {
        textToSpeech.stop();
        textToSpeech.shutdown();
    }


}
